import Vue from 'vue';
import axios from 'axios';
import {
  Loading, Notify,
  QSpinnerGears, debounce,
} from 'quasar';

const notify = (msg) => Notify.create({
  message: msg,
  color: 'negative',
});

const loadingCounter = { count: 0 };

const doHide = debounce(() => {
  Loading.hide();
}, 500);
export const showLoading = () => {
  Loading.show({
    spinner: QSpinnerGears,
    spinnerColor: 'primary',
    spinnerSize: '50px',
    backgroundColor: 'grey-11',
  });
  loadingCounter.count += 1;
};
export const hideLoading = () => {
  loadingCounter.count -= 1;
  if (loadingCounter.count <= 0) {
    loadingCounter.count = 0;
    doHide();
  }
};

export const goLogin = () => {
  window.location.replace('#/login');
};

export const NeedLoginCode = [401, 402, 403];
//手机打包这里需要更换下 baseURL: process.env.SERVER_URL + u,
export const createBase = (u = '') => {
  const service = axios.create({
    baseURL: u,
  });
  service.defaults.timeout = 30000;

  service.interceptors.request.use((config) => {
    if (config.mask !== false) {
      showLoading();
    }

    if (localStorage.Authorization) {
      config.headers.Authorization = localStorage.Authorization;
    }
    return config;
  }, (error) => {
    hideLoading();
    return Promise.reject(error);
  });

  //response interceptor
  service.interceptors.response.use(
    (r) => {
      hideLoading();
      if (r.data) {
        if (r.data.code && r.data.code !== 200) {
          if (r.data.message) {
            notify(`${r.data.message}`);
          }
          if (NeedLoginCode.some((v) => v === r.data.code)) {
            goLogin();
          }
          return Promise.reject(r);
        }
        return r.data;
      }
      return r;
    }, ({ response }) => {
      let msg = '未知错误';
      hideLoading();
      loadingCounter.count = 0;
      if (response) {
        if (response.data) {
          if (!response.data.status) {
            msg = '服务器无响应，请联系管理员！';
          } else {
            msg = `${response.data.message}`;
          }
        } else {
          msg = '';
          switch (response.status) {
            case -1:
              msg += '连接失败';
              break;
            case 500:
              msg += '内部错误';
              break;
            case 404:
              msg += '页面不存在';
              break;
            case 401:
              goLogin();
              break;
            case 403:
              msg += '权限不足';
              break;
            default:
              msg += '未知错误';
          }
        }
      }
      if (msg) { notify(msg); }
      return Promise.reject(response);
    },
  );
  service.createBase = (url = '') => createBase(url);
  return service;
};

export const axiosService = createBase(process.env.BASE_URL);
Vue.prototype.$axios = axiosService;

export const downFile = (url, data) => axiosService({
  url,
  method: 'GET',
  params: data,
  responseType: 'blob',
});

export const exportFile = (url, data) => axiosService({
  url,
  method: 'POST',
  data,
  responseType: 'blob',
});

Vue.prototype.$downFile = downFile;
Vue.prototype.$exportFile = exportFile;

export const uploadFile = (url, parameter) => axiosService({
  url,
  data: parameter,
  method: 'post',
  headers: {
    'Content-Type': 'multipart/form-data',
  },
});

export const imageOcr = (url, parameter) => axiosService({
  url,
  data: parameter,
  method: 'post',
  headers: {
    'Content-Type': 'application/json',
  },
});

export const binaryOcr = (url, parameter) => axiosService({
  url,
  data: parameter,
  method: 'post',
  headers: {
    'Content-Type': 'multipart/form-data',
  },
});
